import config from './config';
const app = getApp();
import loginApi from './api/login';
const baseHost = config.isDebug ? config.baseHostDebug : config.baseHost;
export default {
    http(url, data, method) {
        var that = this;
        // 获取token 
        const token = wx.getStorageSync('flower2025-token');
        const header = {};
        if (token) {
            header['flower2025-token'] = token;
        }
        return new Promise((resolve, reject) => {
            wx.request({
                data,
                method,
                header,
                url: baseHost + url,
                success(res) {
                    if (res.data.errorCode === 401) {
                        // setTimeout(() => {
                        //     loginApi.silentLogin({
                        //         jsCode: ref.code
                        //     }).then(refs => {
                        //         loginApi.updateUserInfo();
                        //     })
                        // },500);
                        wx.showModal({
                            content: '您尚未登录，点击登录后继续。',
                            confirmText: "登录",
                            complete: (res) => {
                                if (res.confirm) {
                                    wx.login({
                                        success: (ref) => {
                                            if (ref.code) {
                                                loginApi.silentLogin({
                                                    jsCode: ref.code
                                                }).then(refs => {
                                                    loginApi.updateUserInfo();
                                                })
                                            }
                                        },
                                    })
                                }
                            }
                        })
                    }
                    resolve(res.data);
                    that.saveToken(res.header)
                },
                fail(err) {
                    wx.showToast({
                        title: "请求失败",
                        icon: "none",
                    })
                    reject(err);
                }
            })
        })
    },
    saveToken(header) {
        if (header['flower2025-token']) {
            wx.setStorage({
                key: "flower2025-token",
                data: header['flower2025-token'],
            })
        }
    },
    /* POST 请求 */
    POST(url, data = {}) {
        return this.http(url, data, 'POST');
    },
    /* GET 请求 */
    GET(url, data = {}) {
        return this.http(url, data, 'GET');
    },
}